<?php
require_once __DIR__ . '/functions.php';
// 获取网站设置
// 如果已登录，跳转到订单页面
if (isLoggedIn()) {
    header('Location: orders.php');
    exit;
}

// 处理登录表单
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'login') {
    $phone = sanitizeInput($_POST['phone'] ?? '');
    $password = $_POST['password'] ?? '';
    $csrf_token = $_POST['csrf_token'] ?? '';
    
    // 验证CSRF令牌
    if (!validateCsrfToken($csrf_token)) {
        $error = '安全令牌无效，请刷新页面重试';
    } elseif (empty($phone) || empty($password)) {
        $error = '请填写完整的登录信息';
    } elseif (!checkLoginAttempts($phone)) {
        $error = '登录尝试次数过多，请15分钟后再试';
    } else {
        $db = getDB();
        $stmt = $db->prepare("SELECT * FROM users WHERE phone = ? AND status = 1");
        $stmt->execute([$phone]);
        $user = $stmt->fetch();
        
        if ($user && passwordVerify($password, $user['password'])) {
        // 检查是否开启注册审批且用户是否已审批
        $approvalSetting = $db->query("SELECT key_value FROM settings WHERE key_name = 'registration_approval'")->fetchColumn();
        if ($approvalSetting && !$user['is_approved']) {
            $error = '您的账号尚未通过审批，请耐心等待';
        }else {
            // 登录成功，清除尝试记录
            clearLoginAttempts($phone);
            
            $_SESSION['user_id'] = $user['id'];
            $_SESSION['username'] = $user['username'];
            $_SESSION['is_admin'] = $user['is_admin'];
            
            // 记录登录日志
            logSecurityEvent('login_success', $user['id']);
            
            // 设置记住登录状态 - 有效期30天
            if (isset($_POST['remember_me']) && $_POST['remember_me'] == '1') {
                $rememberToken = bin2hex(random_bytes(32));
                $expireTime = time() + (30 * 24 * 60 * 60); // 30天
                
                // 保存记住我令牌到数据库
                $db = getDB();
                $stmt = $db->prepare("UPDATE users SET remember_token = ?, token_expire = ? WHERE id = ?");
                $stmt->execute([$rememberToken, date('Y-m-d H:i:s', $expireTime), $user['id']]);
                
                // 设置cookie
                setcookie('remember_token', $rememberToken, $expireTime, '/', '', false, true);
                setcookie('user_id', $user['id'], $expireTime, '/', '', false, true);
            }
            
            if ($user['is_admin']) {
                header('Location: admin/');
            } else {
                header('Location: orders.php');
            }
            exit;
        }} else {
            // 登录失败，记录尝试
            recordLoginAttempt($phone);
            logSecurityEvent('login_failed', null, "手机号: $phone");
            $error = '手机号或密码错误';
        }
        
    }
    
}

// 处理注册表单
// 处理注册表单
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['action']) && $_POST['action'] == 'register') {
    $phone = sanitizeInput($_POST['phone'] ?? '');
    $username = sanitizeInput($_POST['username'] ?? '');
    $password = $_POST['password'] ?? '';
    $confirm_password = $_POST['confirm_password'] ?? '';
    $group_name = sanitizeInput($_POST['group_name'] ?? '');
    $wechat_account = sanitizeInput($_POST['wechat_account'] ?? '');
    $alipay_account = sanitizeInput($_POST['alipay_account'] ?? '');
    $account_holder = sanitizeInput($_POST['account_holder'] ?? '');
    $bank_name = sanitizeInput($_POST['bank_name'] ?? '');
    $bank_card_number = sanitizeInput($_POST['bank_card_number'] ?? '');
    $wechat_nickname = sanitizeInput($_POST['wechat_nickname'] ?? '');
    $csrf_token = $_POST['csrf_token'] ?? '';
    
    // 验证CSRF令牌
    if (!validateCsrfToken($csrf_token)) {
        $error = '安全令牌无效，请刷新页面重试';
    } elseif (empty($phone) || empty($username) || empty($password) || empty($group_name) || 
              empty($wechat_account) || empty($alipay_account) || empty($account_holder) || 
              empty($bank_name) || empty($bank_card_number) || empty($wechat_nickname)) {
        $error = '请填写完整的注册信息';
    } elseif ($password !== $confirm_password) {
        $error = '两次输入的密码不一致';
    } elseif (strlen($password) < 8) {
        $error = '密码长度不能少于8位';
    } elseif (!validatePhone($phone)) {
        $error = '手机号格式不正确';
    } elseif (!validateBankCard($bank_card_number)) {
        $error = '银行卡号格式不正确';
    } elseif (!isset($_FILES['wechat_qr']) || $_FILES['wechat_qr']['error'] !== UPLOAD_ERR_OK) {
        $error = '请上传微信收款码';
    } elseif (!isset($_FILES['alipay_qr']) || $_FILES['alipay_qr']['error'] !== UPLOAD_ERR_OK) {
        $error = '请上传支付宝收款码';
    } else {
        $db = getDB();
        
        // 检查手机号是否已存在
        $stmt = $db->prepare("SELECT id FROM users WHERE phone = ?");
        $stmt->execute([$phone]);
        if ($stmt->fetch()) {
            $error = '该手机号已被注册';
        } else {
            // 检查用户名是否已存在
            $stmt = $db->prepare("SELECT id FROM users WHERE username = ?");
            $stmt->execute([$username]);
            if ($stmt->fetch()) {
                $error = '该用户名已被使用';
            } else {
                // 检查微信昵称是否已存在
                $stmt = $db->prepare("SELECT id FROM users WHERE wechat_nickname = ?");
                $stmt->execute([$wechat_nickname]);
                if ($stmt->fetch()) {
                    $error = '该微信昵称已被使用';
                } else {
                    // 上传微信收款码
                    $wechatQrResult = uploadFile($_FILES['wechat_qr'], 'qr_code');
                    if (!$wechatQrResult['success']) {
                        $error = '微信收款码上传失败: ' . $wechatQrResult['message'];
                    } else {
                        // 上传支付宝收款码
                        $alipayQrResult = uploadFile($_FILES['alipay_qr'], 'qr_code');
                        if (!$alipayQrResult['success']) {
                            // 删除已上传的微信收款码
                            deleteFile($wechatQrResult['filename'], 'qr_code');
                            $error = '支付宝收款码上传失败: ' . $alipayQrResult['message'];
                        } else {
                            // 所有验证通过，注册用户
                            $hashedPassword = passwordHash($password);
                            $stmt = $db->prepare("INSERT INTO users (phone, username, password, group_name, wechat_account, alipay_account, account_holder, bank_name, bank_card_number, wechat_nickname, wechat_qr, alipay_qr) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
                            if ($stmt->execute([$phone, $username, $hashedPassword, $group_name, $wechat_account, $alipay_account, $account_holder, $bank_name, $bank_card_number, $wechat_nickname, $wechatQrResult['filename'], $alipayQrResult['filename']])) {
                                $userId = $db->lastInsertId();
                                
                                // 检查是否开启注册审批
                                $approvalSetting = $db->query("SELECT key_value FROM settings WHERE key_name = 'registration_approval'")->fetchColumn();
                                $needsApproval = $approvalSetting ? true : false;
                                
                                // 如果不需要审批，则自动审批
                                if (!$needsApproval) {
                                    $db->prepare("UPDATE users SET is_approved = 1 WHERE id = ?")->execute([$userId]);
                                }
                                
                                logSecurityEvent('register_success', $userId);
                                $success = $needsApproval ? '注册成功，请等待管理员审批' : '注册成功，请登录';
                            }  else {
                                // 注册失败，删除已上传的图片
                                deleteFile($wechatQrResult['filename'], 'qr_code');
                                deleteFile($alipayQrResult['filename'], 'qr_code');
                                logSecurityEvent('register_failed', null, "手机号: $phone");
                                $error = '注册失败，请重试';
                            }
                        }
                    }
                }
            }
        }
    }
}

// 获取群组选项
$groupOptions = getConfigOptions('group_name');

include __DIR__ . '/header.php';
?>

<div class="container mt-5">
    <div class="row justify-content-center">
        <div class="col-md-8">
            <div class="card shadow-lg border-0 rounded-4">
                <div class="card-header bg-primary text-white text-center rounded-top-4">
                    <h3 class="mb-0">
                        <i class="bi bi-box-seam"></i> <?php echo htmlspecialchars($settings['site_name'] ?? '报单系统'); ?>
                    </h3>
                    <p class="mb-0 small">专业的订单管理与结算平台</p>
                </div>
                <div class="card-body p-4">
                    <?php if (isset($error)): ?>
                        <div class="alert alert-danger alert-dismissible fade show" role="alert">
                            <i class="bi bi-exclamation-triangle-fill"></i> <?php echo htmlspecialchars($error); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>
                    
                    <?php if (isset($success)): ?>
                        <div class="alert alert-success alert-dismissible fade show" role="alert">
                            <i class="bi bi-check-circle-fill"></i> <?php echo htmlspecialchars($success); ?>
                            <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
                        </div>
                    <?php endif; ?>

                    <!-- 登录表单 -->
                    <div id="loginForm" class="tab-content">
                        <form method="POST" class="needs-validation" novalidate>
                            <input type="hidden" name="action" value="login">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="mb-4">
                                <label for="phone" class="form-label">
                                    <i class="bi bi-telephone-fill text-primary"></i> 手机号
                                </label>
                                <input type="tel" class="form-control form-control-lg" id="phone" name="phone" 
                                       placeholder="请输入手机号" required pattern="^1[3-9]\d{9}$"
                                       value="<?php echo htmlspecialchars($phone ?? ''); ?>">
                                <div class="invalid-feedback">
                                    请输入正确的手机号
                                </div>
                            </div>
                            
                            <div class="mb-4">
                                <label for="password" class="form-label">
                                    <i class="bi bi-lock-fill text-primary"></i> 密码
                                </label>
                                <input type="password" class="form-control form-control-lg" id="password" name="password" 
                                       placeholder="请输入密码" required minlength="6">
                                <div class="invalid-feedback">
                                    密码长度不能少于6位
                                </div>
                            </div>
                            
                            <div class="mb-3">
                                <div class="form-check">
                                    <input class="form-check-input" type="checkbox" id="remember_me" name="remember_me" value="1" checked>
                                    <label class="form-check-label" for="remember_me">
                                        <i class="bi bi-check2-square"></i> 记住我（30天内免登录）
                                    </label>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-primary btn-lg">
                                    <i class="bi bi-box-arrow-in-right"></i> 登录
                                </button>
                            </div>
                        </form>
                        
                        <div class="text-center mt-3">
                            <p class="mb-2">还没有账号？</p>
                            <button type="button" class="btn btn-outline-success" onclick="showRegister()">
                                <i class="bi bi-person-plus"></i> 立即注册
                            </button>
                        </div>
                    </div>

                    <!-- 注册表单 -->
                    <!-- 注册表单 -->
                    <div id="registerForm" class="tab-content" style="display: none;">
                        <form method="POST" enctype="multipart/form-data" class="needs-validation" novalidate>
                            <input type="hidden" name="action" value="register">
                            <input type="hidden" name="csrf_token" value="<?php echo generateCsrfToken(); ?>">
                            
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="reg_phone" class="form-label">
                                            <i class="bi bi-telephone-fill text-success"></i> 手机号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="tel" class="form-control" id="reg_phone" name="phone" 
                                               placeholder="请输入手机号" required pattern="^1[3-9]\d{9}$">
                                        <div class="invalid-feedback">
                                            请输入正确的手机号
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="reg_username" class="form-label">
                                            <i class="bi bi-person-fill text-success"></i> 用户名 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="reg_username" name="username" 
                                               placeholder="请输入用户名" required minlength="2" maxlength="20">
                                        <div class="invalid-feedback">
                                            用户名长度2-20个字符
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="reg_password" class="form-label">
                                            <i class="bi bi-lock-fill text-success"></i> 密码 <span class="text-danger">*</span>
                                        </label>
                                        <input type="password" class="form-control" id="reg_password" name="password" 
                                               placeholder="请输入密码" required minlength="8">
                                        <div class="invalid-feedback">
                                            密码长度不能少于8位
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="confirm_password" class="form-label">
                                            <i class="bi bi-lock-fill text-success"></i> 确认密码 <span class="text-danger">*</span>
                                        </label>
                                        <input type="password" class="form-control" id="confirm_password" name="confirm_password" 
                                               placeholder="请再次输入密码" required>
                                        <div class="invalid-feedback">
                                            两次输入的密码不一致
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="group_name" class="form-label">
                                            <i class="bi bi-people text-success"></i> 所在群组 <span class="text-danger">*</span>
                                        </label>
                                        <select class="form-select" id="group_name" name="group_name" required>
                                            <option value="">请选择所在群组</option>
                                            <?php foreach ($groupOptions as $group): ?>
                                                <option value="<?php echo htmlspecialchars($group['option_value']); ?>">
                                                    <?php echo htmlspecialchars($group['option_label']); ?>
                                                </option>
                                            <?php endforeach; ?>
                                        </select>
                                        <div class="invalid-feedback">
                                            请选择所在群组
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="wechat_nickname" class="form-label">
                                            <i class="bi bi-wechat text-success"></i> 微信昵称 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="wechat_nickname" name="wechat_nickname" 
                                               placeholder="请输入您的微信昵称" required>
                                        <div class="invalid-feedback">
                                            请输入微信昵称
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="wechat_account" class="form-label">
                                            <i class="bi bi-wechat text-success"></i> 微信号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="wechat_account" name="wechat_account" 
                                               placeholder="请输入微信号" required>
                                        <div class="invalid-feedback">
                                            请输入微信号
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="alipay_account" class="form-label">
                                            <i class="bi bi-alipay text-success"></i> 支付宝账号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="alipay_account" name="alipay_account" 
                                               placeholder="请输入支付宝账号" required>
                                        <div class="invalid-feedback">
                                            请输入支付宝账号
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="account_holder" class="form-label">
                                            <i class="bi bi-person-badge text-success"></i> 开户人姓名 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="account_holder" name="account_holder" 
                                               placeholder="请输入银行卡开户人姓名" required>
                                        <div class="invalid-feedback">
                                            请输入开户人姓名
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="bank_name" class="form-label">
                                            <i class="bi bi-bank text-success"></i> 银行名称 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="bank_name" name="bank_name" 
                                               placeholder="请输入银行名称" required>
                                        <div class="invalid-feedback">
                                            请输入银行名称
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <!-- 在注册表单的银行卡号输入字段，修改为： -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="bank_card_number" class="form-label">
                                            <i class="bi bi-credit-card text-success"></i> 银行卡号 <span class="text-danger">*</span>
                                        </label>
                                        <input type="text" class="form-control" id="bank_card_number" name="bank_card_number" 
                                               placeholder="请输入银行卡号（纯数字）" required 
                                               pattern="\d{16,23}"
                                               oninput="formatBankCard(this)"
                                               maxlength="23">
                                        <div class="invalid-feedback">
                                            请输入正确的银行卡号（16-19位数字）
                                        </div>
                                    </div>
                                </div>
                            </div>
                    
                            <!-- 收款码上传部分 -->
                            <div class="row">
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="wechat_qr" class="form-label">
                                            <i class="bi bi-qr-code text-success"></i> 微信收款码 <span class="text-danger">*</span>
                                        </label>
                                        <input type="file" class="form-control" id="wechat_qr" name="wechat_qr" 
                                               accept="image/*" required>
                                        <div class="form-text">
                                            请上传清晰的微信收款码图片，支持 JPG、PNG 格式，最大 5MB
                                        </div>
                                        <div class="invalid-feedback">
                                            请上传微信收款码
                                        </div>
                                    </div>
                                </div>
                                <div class="col-md-6">
                                    <div class="mb-3">
                                        <label for="alipay_qr" class="form-label">
                                            <i class="bi bi-qr-code text-success"></i> 支付宝收款码 <span class="text-danger">*</span>
                                        </label>
                                        <input type="file" class="form-control" id="alipay_qr" name="alipay_qr" 
                                               accept="image/*" required>
                                        <div class="form-text">
                                            请上传清晰的支付宝收款码图片，支持 JPG、PNG 格式，最大 5MB
                                        </div>
                                        <div class="invalid-feedback">
                                            请上传支付宝收款码
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <div class="d-grid gap-2">
                                <button type="submit" class="btn btn-success btn-lg">
                                    <i class="bi bi-person-check"></i> 注册
                                </button>
                            </div>
                        </form>
                        
                        <div class="text-center mt-3">
                            <p class="mb-2">已有账号？</p>
                            <button type="button" class="btn btn-outline-primary" onclick="showLogin()">
                                <i class="bi bi-box-arrow-in-left"></i> 返回登录
                            </button>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

<script>
function showRegister() {
    document.getElementById('loginForm').style.display = 'none';
    document.getElementById('registerForm').style.display = 'block';
    // 重新验证表单
    const forms = document.querySelectorAll('.needs-validation');
    forms.forEach(form => {
        form.classList.remove('was-validated');
    });
}

function showLogin() {
    document.getElementById('loginForm').style.display = 'block';
    document.getElementById('registerForm').style.display = 'none';
    // 重新验证表单
    const forms = document.querySelectorAll('.needs-validation');
    forms.forEach(form => {
        form.classList.remove('was-validated');
    });
}

// 表单验证
(function() {
    'use strict';
    window.addEventListener('load', function() {
        const forms = document.querySelectorAll('.needs-validation');
        const password = document.getElementById('reg_password');
        const confirmPassword = document.getElementById('confirm_password');
        const wechatQr = document.getElementById('wechat_qr');
        const alipayQr = document.getElementById('alipay_qr');
        
        // 确认密码验证
        if (confirmPassword) {
            confirmPassword.addEventListener('input', function() {
                if (password.value !== confirmPassword.value) {
                    confirmPassword.setCustomValidity('密码不一致');
                } else {
                    confirmPassword.setCustomValidity('');
                }
            });
        }
        
        // 文件类型验证
        function validateFileType(fileInput) {
            const file = fileInput.files[0];
            if (file) {
                const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
                if (!allowedTypes.includes(file.type)) {
                    fileInput.setCustomValidity('请上传 JPG、PNG、GIF 或 WebP 格式的图片');
                    return false;
                }
                
                // 检查文件大小 (最大5MB)
                if (file.size > 5 * 1024 * 1024) {
                    fileInput.setCustomValidity('文件大小不能超过5MB');
                    return false;
                }
                
                fileInput.setCustomValidity('');
                return true;
            }
            return true;
        }
        
        // 微信收款码验证
        if (wechatQr) {
            wechatQr.addEventListener('change', function() {
                validateFileType(this);
            });
        }
        
        // 支付宝收款码验证
        if (alipayQr) {
            alipayQr.addEventListener('change', function() {
                validateFileType(this);
            });
        }
        
        Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
                // 在提交前验证文件
                if (wechatQr) validateFileType(wechatQr);
                if (alipayQr) validateFileType(alipayQr);
                
                if (form.checkValidity() === false) {
                    event.preventDefault();
                    event.stopPropagation();
                }
                form.classList.add('was-validated');
            }, false);
        });
    }, false);
})();

// 银行卡号格式化函数（实时格式化显示，但存储纯数字）
function formatBankCard(input) {
    // 获取光标位置
    let cursorPos = input.selectionStart;
    
    // 移除所有非数字字符
    let value = input.value.replace(/\D/g, '');
    
    // 格式化显示：每4位加一个空格
    let formattedValue = '';
    for (let i = 0; i < value.length; i++) {
        if (i > 0 && i % 4 === 0) {
            formattedValue += ' ';
        }
        formattedValue += value[i];
    }
    
    // 更新输入框值
    input.value = formattedValue;
    
    // 调整光标位置（考虑新增的空格）
    let addedSpaces = Math.floor(cursorPos / 4);
    let newCursorPos = cursorPos + addedSpaces;
    input.setSelectionRange(newCursorPos, newCursorPos);
}

// 在表单提交前，移除银行卡号中的空格
document.addEventListener('DOMContentLoaded', function() {
    const forms = document.querySelectorAll('form');
    forms.forEach(form => {
        form.addEventListener('submit', function(e) {
            const bankCardInput = form.querySelector('#bank_card_number');
            if (bankCardInput) {
                // 移除所有空格，只保留纯数字
                bankCardInput.value = bankCardInput.value.replace(/\s/g, '');
            }
        });
    });
});

// 页面加载时，如果已有银行卡号，进行格式化显示
document.addEventListener('DOMContentLoaded', function() {
    const bankCardInput = document.getElementById('bank_card_number');
    if (bankCardInput && bankCardInput.value) {
        formatBankCard(bankCardInput);
    }
});
</script>

<?php include __DIR__ . '/footer.php'; ?>